

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;

public class DownloadRunnableImpl implements Runnable{
    private Socket socket;

    public DownloadRunnableImpl(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            String filePath = "E:"+File.separator+"beauty.jpg";
            File file = new File(filePath);
            String fileName = file.getName();
            long fileLength = file.length();
            System.out.println("服务端待下载文件：" + fileName + "，其大小为：" + fileLength);

            FileInputStream fileInputStream = new FileInputStream(filePath);

            OutputStream outputStream = socket.getOutputStream();

            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

            dataOutputStream.writeUTF(fileName);
            dataOutputStream.writeLong(fileLength);
            dataOutputStream.flush();

            byte[] buf = new byte[1024 * 1];
            int len = 0;
            while ((len = fileInputStream.read(buf)) != -1) {
                dataOutputStream.write(buf, 0, len);
            }

            dataOutputStream.flush();
            fileInputStream.close();
            socket.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

}

